/** bidding.js */
var count_down = require('../../utils/countDown.js');
var util = require('../../utils/util.js');
var regexp = require('../../utils/regexpUtil.js');
var pay = require('../../utils/pay.js');
var calc = require('../../utils/calc.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    host: getApp().globalData.host,
    biddingId: '',
    bidding: {},
    countDown:{},
    market:{},
    showTab:'desc',
    quotes:[],
    quoteAmount:0,
    isOpen:true,
    isShared:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if(typeof(options.isShared)!='undefined')
      this.data.isShared = options.isShared;
    that.setData({
      biddingId: options.biddingId,
      isShared:this.data.isShared
    }),

    wx.request({
      url: that.data.host + '/webapp/business/getBidding.html?biddingId=' + that.data.biddingId,
      header: getApp().globalData.header,
      success: function (res) {
        var resData = res.data;
        resData.validTimeView = util.formatTime(resData.validTime);
        resData.expireTimeView = util.formatTime(resData.expireTime);
        resData.desc = regexp.regexpImg(resData.desc);
        //设置出价初始价
        resData.quoteAmount = resData.currentAmount + resData.buyerIncrement;
        //count_down.countDown('',resData.expireTime,that,resData.biddingCode);
        //非正在进行的竞拍，不得出价，不得围观
        let isopen = resData.status=='InProcess'?true:false;
        that.setData({
          bidding: resData,
          quoteAmount:resData.quoteAmount,
          isOpen:isopen
        });
        that.getMarket(resData.marketId);
        count_down.countDownSecond(resData.countdown,that, resData.biddingCode);
      }
    })
    this.quoteLogs(this.data.biddingId);
  },
  getMarket:function(marketId){
    var that = this;
    wx.request({
      url: that.data.host + '/webapp/business/getMarket.html?marketId=' + marketId,
      header: getApp().globalData.header,
      success: function (res) {
        var resData = res.data;
        resData.openTimeAM = util.formatSqlTime(resData.openTimeAM);
        resData.closeTimeAM = util.formatSqlTime(resData.closeTimeAM);
        resData.openTimePM = util.formatSqlTime(resData.openTimePM);
        resData.closeTimePM = util.formatSqlTime(resData.closeTimePM);
        that.setData({
          market: resData
        });
      }
    })
  },
  quoteLogs:function(biddingId){
    var that = this;
    wx.request({
      url: that.data.host + '/webapp/business/quoteLogs.html?biddingId=' + biddingId,
      header: getApp().globalData.header,
      success: function (res) {
        if (typeof(res.data)=='undefined'||res.data.length<1) return;
        for (var i = 0; i < res.data.length; i++) {
          res.data[i].createTime = util.formatTimeStamp(res.data[i].createTime);
        }        
        that.setData({
          quotes: res.data
        });
      }
    })
  },
  countDownFinish:function(biddingCode){//休市处理函数
    this.setData({
      isOpen: false
    });
  },
  showDesc:function(){
    this.setData({
      showTab: 'desc'
    });
  },
  showRecord:function(){
    this.setData({
      showTab: 'record'
    });
  },
  showInstruction:function(){
    this.setData({
      showTab: 'instruction'
    });
  },
  doMargin:function(){
    var that = this;
    if (getApp().globalData.platUser == null) {//用户未登录 跳转至登录页面
      wx.navigateTo({
        url: '../login/login'
      });
    }else{
      if (!this.data.isOpen) {
        wx.showToast({
          title: '已休市，请注意市场开放时间',
          icon: 'loading',
          duration: 2000
        });
        return;
      }
      wx.showModal({
        title: '缴纳保证金：' + that.data.bidding.buyerMarginAmount + '元',
        content: '若竞价未成功，保证金自动退回;\r\n若竞价成功，保证金转为货款，您需要支付剩余货款。\r\n点击[确认]视为理解并同意竞价出价协议。',
        success: function(res) {
          if(res.confirm) {
             wx.request({
              url: getApp().globalData.host + 'webapp/business/doMargin.html',
              header: getApp().globalData.header,
              method:'POST',
              data:{biddingId:that.data.biddingId},
              success: function (res) {
                if (typeof (res.data) != 'undefined' && typeof (res.data.orderId) != 'undefined')
                  pay.specialPay(res.data);
                else{
                  wx.showToast({
                    title: res.data.errorMsg,
                    icon: 'success',
                    duration: 2000
                  });
                }
              },
              fail: function (res) { },
              complete: function (res) { }
           })

          }else if(res.cancel) {//do nothing
            
          }
        }
      })
    }

  },
  //按钮减少出价，最低价不得低于当前价+加价幅度，每次减少加价幅度
  reduce:function(){
    var changeQuote = calc.sub(this.data.quoteAmount,this.data.bidding.buyerIncrement);
    if(changeQuote >= this.data.bidding.quoteAmount){
      this.data.quoteAmount = changeQuote;
    }else{
      this.data.quoteAmount = this.data.bidding.quoteAmount;
    }
    this.setData({
      quoteAmount:this.data.quoteAmount
    });
  },
  //按钮加价，按当前价+加价幅度
  add:function(){
    this.setData({
      quoteAmount:calc.add(this.data.quoteAmount + this.data.bidding.buyerIncrement)
    });
  },
  //手动修改出价金额 ，最低价不得低于当前价+加价幅度
  quoteChange:function(e){
    var reg = /^[1-9]+[0-9]*]*$/; //判断正整数
    var changeQuote = e.detail.value;
    if(reg.test(changeQuote)){
      changeQuote = parseInt(changeQuote);
      if(changeQuote<this.data.bidding.quoteAmount) 
        changeQuote=this.data.bidding.quoteAmount;
      this.setData({
        quoteAmount: changeQuote
      });
    }else{
      this.setData({
        quoteAmount: this.data.quoteAmount
      });
    }
  },
  doQuote:function(){
    var that = this;
    if (!this.data.isOpen) {
      wx.showToast({
        title: '已休市，请注意市场开放时间',
        icon: 'loading',
        duration: 2000
      });
      return;
    }
    wx.showModal({
      title: '您的出价金额为：' + that.data.quoteAmount + '元',
      content: '若您竞价成功\r\n需要支付 [出价金额] 扣除 [保证金] 之后的剩余货款；\r\n如未支付，您缴纳的保证金将赔付给送拍方。',
      success: function(res) {
        if(res.confirm) {
           wx.request({
            url: getApp().globalData.host + 'webapp/business/doQuote.html',
            header: getApp().globalData.header,
            method:'POST',
            data:{biddingId:that.data.biddingId,quoteAmount:that.data.quoteAmount},
            success: function (res) {
              if (typeof (res.data) != 'undefined' && res.data.errorCode==0){//创建记录成功
                wx.showToast({
                  title: '出价成功',
                  icon: 'success',
                  duration: 2000
                });
                //重新加载出价记录
                that.quoteLogs(that.data.biddingId);
              }else{
                wx.showToast({
                  title: res.data.errorMsg,
                  icon: 'success',
                  duration: 2000
                });
              }
            },
            fail: function (res) { },
            complete: function (res) { }
         })

        }else if(res.cancel) {//do nothing
          
        }
      }
    })
  },  
  //分享该页面
  onShareAppMessage: function () {
    return {
      title: '[分享竞价] ' +  this.data.bidding.name,
      path: '/pages/bidding/bidding?isShared=true&biddingId=' + this.data.biddingId
    }
  },
  //返回首页（分享页面时，后退无用）
  goHome:function(){
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  //拨打客服电话
  contactService:function(){
    wx.makePhoneCall({
      phoneNumber: getApp().globalData.servicePhone
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  }
})